﻿using Company.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Hardware.Detector
{
    public abstract class DetectorBase : IDetector
    {
        public bool Initialized { get; set; }

        public abstract event Action<DetectorImage> OnTrigger;

        public DetectorConfig Config { get; private set; }

        public bool Close()
        {
            if (Initialized)
            {
                if (DoClose())
                {
                    Initialized = false;
                    return true;
                }
            }

            return false;
        }

        public bool Initialize(IDetectorConfigProvider provider)
        {
            Config = provider.DetectorConfig;
            provider.OnChanged += () =>
            {
                Logs.LogInfo($"平板探测器重新初始化 Width：{provider.DetectorConfig.Width}，Height：{provider.DetectorConfig.Height}");
                DoInitialize();
            };


            if (Initialized)
            {
                Logs.LogError(new InvalidOperationException("平板探测器重复初始化！"));
            }

            if (DoInitialize())
            {
                Initialized = true;
                return true;
            }

            return false;
        }

        public bool Grab()
        {
            if (!Initialized)
            {
                throw new InvalidOperationException("请先初始化平板探测器！");
            }

            if (DoGrab())
            {
                return true;
            }

            return false;
        }

        // 具体实现由子类去完成
        public abstract bool DoInitialize();
        public abstract bool DoClose();

        /// <summary>
        /// 抓取数据，平板探测器是持续抓取数据
        /// </summary>
        /// <returns></returns>
        public abstract bool DoGrab();


    }
}
